// 配置跨越携带cookie 和证书
import axios from 'axios';
import storage from '@/utils/ado-self/ado-storage';

axios.defaults.withCredentials = true;
axios.defaults.timeout = 50000;
window._UIDesingerAxios = axios;
window._xvueAxios = axios;

// 请求预处理
axios.interceptors.request.use(
  config => {
    // 本地token，配合src/logic/refreshToken.js自动刷新
    const envInfo = storage.get('visual_components_token') || window.envInfo;
    const { env } = envInfo;
    let { token } = envInfo;

    const header = {};
    if (typeof token === 'object') {
      header['client-code'] = token.clientCode;
      header['uc-code'] = token.ucCode;
      header.tenantCode = token.tenantId;
      token = token.token;
    }

    const headers = {
      lang: 'zh_CN',
      'version-number': 'V1R1C00_1',
      'client-code': header['client-code'],
      'tenant-code': header.tenantCode,
      tenantCode: header.tenantCode,
      tenantId: header.tenantCode,
      'uc-code': header['uc-code'],
      'gc-authentication': token,
    };
    for (const i in headers) {
      if (!config.headers[i]) {
        config.headers[i] = headers[i];
      }
    }

    if (!config.url.startsWith('http') && !config.url.startsWith('/sdv/')) {
      config.url = `/${env}${config.url}`;
    }

    // 本地调试
    if (window.setAxiosConfig) {
      window.setAxiosConfig(config);
    }
    return config;
  },
  err => Promise.reject(err),
);

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.constructor.name === 'Cancel') {
      return error;
    }

    const status = error.response && error.response.status;
    if (status === 401) {
      // 未登录，重新刷新token
      window.reFreshToken && window.reFreshToken(window.visualEnv);
    }
    return Promise.reject(error);
  },
);
